import React, { useEffect, useState } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
import Item from './components/Item/Item'
import './App.css'
export default function App() {
  const [todos, setTodos] = useState([
    {
      id: 3,
      todoName: '爱党',
      isDone: true,
    },
    {
      id: 2,
      todoName: '爱国',
      isDone: true,
    },
    {
      id: 1,
      todoName: '嘿嘿嘿',
      isDone: false,
    },
  ])

  useEffect(() => {
    const addId = PubSub.subscribe('add', (topic, todoName) => {
      // 根据任务名,创建任务对象
      const todo = {
        // id的要求是整数,但是不能重复
        // 如果数组有数据,则找到第一个的id+1. 如果数组没有长度,则第一条数据直接设置为1
        id: todos.length ? todos[0].id + 1 : 1,
        todoName,
        isDone: false,
      }

      setTodos((todos) => {
        //这个todos一定是最新的数据
        // 现在使用的是回调自己的todos数据,不使用app的todos也就没有闭包问题了
        const newTodos = [...todos]
        newTodos.unshift(todo)
        return newTodos
      })
    })
    return () => {
      PubSub.unsubscribe(addId)
    }
  }, [])
  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <div>
          <List>
            {todos.map((item) => {
              return <Item todo={item} key={item.id}></Item>
            })}
          </List>
          <Footer></Footer>
        </div>
      </div>
    </div>
  )
}
